<?php

namespace App\Http\Controllers\V1\API;

use App\Http\Controllers\V1\API\BaseController;
use App\Models\V1\Clothes;
use App\Models\V1\ClotheSize;
use App\Models\V1\NewStudent;
use App\Models\V1\ResultClothes;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Auth;
use Log;

class ApplyClothController extends BaseController
{

    /***
     * 获取校服数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getClothes(Request $request) {
        $code = $request->get('userID');

        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        if (empty($code) || !isset($code)) {
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = '参数不正确';
        }else{
            $student = $this->getStudentInfo($code);
            if (empty($student) || !isset($student)) {
                $result['errorCode'] = Response::HTTP_NOT_FOUND;
                $result['errorMsg'] = '用户不存在';
            }else {
                $clothes = $this->getClothList($code);
                if ($clothes->isEmpty()) {
                    $result['errorCode'] = Response::HTTP_OK;
                    $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
                }else {
                    // 格式化数据
                    $resultClothes = array();
                    $resultClothes['isSubmit'] = $this->isSubmit($code);
                    $clothList = array();
                    foreach ($clothes as $item) {
                        $formatCloth = array();
                        $formatCloth['clothCode'] = $item['code'];
                        $formatCloth['clothName'] = $item['name'];
                        $formatCloth['picturePath'] = isset($item['picture'])?$item['picture']:'';
                        $clothSizes = $this->getClothSizeList($item['code'],$code);
                        $resultSizes = array();
                        foreach ($clothSizes as $size) {
                            $formatSize = array();
                            $formatSize['sizeCode'] = $size['code'];
                            $formatSize['sizeName'] = $size['name'];
                            $formatSize['heightLow'] = $size['height_low'];
                            $formatSize['heightHigh'] = $size['height_high'];
                            $formatSize['size'] = $size['size'];
                            $formatSize['length'] = $size['cloth_length'];
                            $formatSize['bust'] = $size['bust'];
                            $selectedSize = $this->getSelectedClothSize($code,$item['code']);
                            if ($selectedSize === $size['code']) {
                                $formatSize['isSelected'] = true;
                            }
                            array_push($resultSizes,$formatSize);
                        }
                        $formatCloth['sizes'] = $resultSizes;
                        array_push($clothList, $formatCloth);
                    }
                    $resultClothes['clothList'] = $clothList;
                    $result['errorCode'] = Response::HTTP_OK;
                    $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
                    $result['data'] = $resultClothes;
                }
            }
        }
        return $this->sendResponse($result, $result['errorCode']);
    }


    /****
     * 更新尺码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function selectClothSizes(Request $request) {
        $code = $request->get('userID');
        $sizes = $request->get('sizes');
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
        );
        if ($request->method() === 'POST') {
            $student = $this->getStudentInfo($code);
            if (empty($student) || !isset($student)) {
                $result['errorCode'] = Response::HTTP_NOT_FOUND;
                $result['errorMsg'] = '用户不存在';
            }else {
                if (count($sizes) > 0){
                    $rspObj = $this->handleUpdate($code,$sizes);
                    if ($rspObj) {
                        $result['errorCode'] = Response::HTTP_OK;
                        $result['errorMsg'] = '校服尺码更新成功';
                    }
                    else {
                        $result['errorCode'] = Response::HTTP_BAD_REQUEST;
                        $result['errorMsg'] = '校服尺码更新失败';
                    }
                }else {
                    $result['errorCode'] = Response::HTTP_BAD_REQUEST;
                    $result['errorMsg'] = '参数不正确';
                }
            }
        }
        return $this->sendResponse($result, $result['errorCode']);
    }


    /***
     * 获取校服列表
     * @param $code
     * @return mixed
     */
    private function getClothList($code){
        $arrival_code = $this->getArrivalCode($code);
        $student = $this->getStudentInfo($code);
        $sex = $student['sex'];
        if (strlen($arrival_code)>0){
            if ($sex == 1){
                $data = Clothes::where('arrival_code',$arrival_code)->whereIn('sex_limit',[1,2])->get();
            }else {
                $data = Clothes::where('arrival_code',$arrival_code)->whereIn('sex_limit',[1,3])->get();
            }
        }else {
            if ($sex == 1){
                $data = Clothes::whereIn('sex_limit',[1,2])->get();
            }else {
                $data = Clothes::whereIn('sex_limit',[1,3])->get();
            }
        }
        return $data;
    }

    /****
     * 根据校服代码获取校服尺码
     * @param $code
     * @return string
     */
    private function getClothSizeList($code,$exam_code)
    {
        $arrival_code = $this->getArrivalCode($exam_code);
        $sizes = ClotheSize::where(['cloth_code'=>$code,'arrival_code'=>$arrival_code])->get();
        return $sizes;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCode($code)
    {
        $student = NewStudent::where('exam_code',$code)->first();
        return $student['arrival_code'];
    }

    /***
     * 根据考试号获取学生基础信息
     * @param $code
     */
    private function getStudentInfo($code){
        $student = NewStudent::where('exam_code',$code)->first();
        return $student;
    }


    /***
     * 根据学生代码与校服代码获取选中的尺码
     * @param $code
     * @param $cloth_code
     * @return mixed
     */
    private function getSelectedClothSize($code,$cloth_code){
        $resultSize = ResultClothes::where(['exam_code'=>$code,'cloth_code'=>$cloth_code])->first();

        $selectedSize='';
        //没有选择尺码，给一个默认尺码
        if (empty($resultSize) || !isset($resultSize)) {
            $student = $this->getStudentInfo($code);
            $height = isset($student['height'])?$student['height']:0;
            $arrival_code = $this->getArrivalCode($code);
            $size = ClotheSize::where(['cloth_code'=>$cloth_code,'arrival_code'=>$arrival_code])
                ->where('height_low', '<=', $height)
                ->where('height_high', '>=', $height)
                ->first();
            if (!empty($size) || isset($size)) {
                $selectedSize = $size['code'];
            }else {
                $size = ClotheSize::where(['cloth_code'=>$cloth_code,'arrival_code'=>$arrival_code])
                    ->first();
                $selectedSize = $size['code'];
            }
        }else {
            $selectedSize = $resultSize['size_code'];
        }
        return $selectedSize;
    }

    /***
     * 学生是否已选择过校服
     * @param $code
     */
    private function isSubmit($code){
        $resultSize = ResultClothes::where(['exam_code'=>$code])->get()->toArray();
        if (count($resultSize)>0) {
            return true;
        }
        return false;
    }

    /***
     * 更新
     * @param $code
     * @param $sizes
     * @return mixed
     */
    private function handleUpdate($code,$sizes){
         foreach ($sizes as $item) {
             $cloth_code = $item['clothCode'];
             $size_code = $item['sizeCode'];
             $updateData = [
                 'exam_code' =>$code,
                 'cloth_code' =>$cloth_code,
                 'size_code' =>$size_code,
             ];
             $rspObj = ResultClothes::updateOrCreate(['exam_code'=>$code,'cloth_code'=>$cloth_code],$updateData);
         }
        return $rspObj;
    }
}
